import React, { useEffect } from "react";
import { View } from '@tarojs/components'
import TabBar from "../../../../components/tabbar";
import Taro, { getMenuButtonBoundingClientRect, eventCenter, } from "@tarojs/taro";
import { Image, Field, Icon, Row, Col, Cell, NavBar, Button, Toast } from "@antmjs/vantui";
import { useState } from "react";
import { HOST, getUserInfo } from "../../../../utils/const";
import { edituser, uploadFile } from '../../../../https/mine';

import './index.scss'

const defaultImg = 'https://img.yzcdn.cn/vant/cat.jpeg'

const Mine = () => {
  const btn = getMenuButtonBoundingClientRect();
  const [userName, setUserName] = useState(null)
  const [img, setImg] = useState(null)

  useEffect(() => {
    if (JSON.stringify(getUserInfo()) != '{}') {
      setUserName(getUserInfo()?.nickname)
      setImg(getUserInfo()?.avatar? getUserInfo()?.avatar : defaultImg)
    }
  }, [])

  const myHeaderImg = () => {
    return (
      <View >
        <Image width={150} height={150} radius={'50%'} src={img? HOST+img : defaultImg} />
        <Button
          className="person-img-btn"
          openType="chooseAvatar"
          onChooseAvatar={onChooseAvatar}></Button>
      </View>
    )
  }

  const onChooseAvatar = ({ detail }) => {
    Taro.getFileSystemManager().readFile({
      filePath: detail?.avatarUrl,
      encoding: 'base64',
      success: res => {
        Taro.uploadFile({
          url: HOST+'/api/uploadFile', //仅为示例，非真实的接口地址
          filePath: detail?.avatarUrl,
          name: 'file',
          formData: {
            'file': res.data
          },
          success (res){
            const data = JSON.parse(res.data)
            setImg(data?.url)
          }
        })
      },
      fail: err => {
      }
    })
    
  };

  const submitData = () => {
    if (!img) {
      Toast.show({ message: '请上传图片！' })
    }
    if (!userName) {
      Toast.show({ message: '请上传图片！' })
    }
    Taro.showLoading({ title: '加载中' })
    edituser({ userId: getUserInfo()?.user_id, nickname: userName, avatar: img }).then((res) => {
      Taro.hideLoading()
      if (res?.success) {
        Taro.navigateBack({
          success() {
            eventCenter.trigger("updateUserInfo");
          },
        })
      }
    })
  }


  return (
    <View className="mymaterial-view">
      <NavBar title='我的资料' leftArrow onClickLeft={() => Taro.navigateBack()} leftText={'返回'} fixed />
      <View style={{ paddingTop: btn.bottom + 20 }}>
        <Cell title="我的头像" isLink={false} size={'large'} value={myHeaderImg()} />
        <Cell
          title="我的昵称"
          value={<Field
            inputAlign="right"
            value={userName}
            placeholder="请输入昵称"
            border={false}
            onChange={(e) => setUserName(e.detail)}
          />}
          size={'large'}
        />
      </View>
      <View style={{ marginTop: 20, display: 'flex', width: '90%', margin: '0 auto', paddingTop: 20 }}>
        <Button onClick={submitData} type='primary' style={{ width: '100%', margin: '0 auto' }}>确认</Button>
      </View>
    </View>
  )
}


export default Mine